//#[macro_use]
//extern crate clap;
#[macro_use]
extern crate lazy_static;
extern crate chrono;
extern crate colog;
// use glob::glob;
use colored::Colorize;
use clap::Parser;
use chrono::Local;
use std::io::Write;

// extern crate md5;
// extern crate walkdir;
// extern crate regex;
// extern crate threadpool;
// extern crate tempfile;
mod download;
// use download::Do;
use log::info;

//#[derive(clap::Args)]
//#[command(version = "1.2", author = "Qingluan")]
#[derive(Parser, Debug)] // requires `derive` feature
#[clap(version = "1.2", author = "Qingluan")]
struct Opts {
    #[clap(short = 'u', long = "url", multiple = true)]
    urls: Vec<String>,
    #[clap(short = 't', long = "thread", default_value = "10")]
    thread: i32,

    #[clap(short = 'f', long = "type", default_value = "[NONE]")]
    file_type: String,

    #[clap(short = 'o', long = "output-dir", default_value = "~/Downloads/c-down")]
    output_dir: String,
}



fn log_inif() {
    let mut clog = colog::builder();
    clog.format(|buf, record| {
        writeln!(
            buf,
            "{} [{}] - {}",
            Local::now().format("%Y-%m-%dT%H:%M:%S"),
            record.level(),
            record.args()
        )
    });
    // clog.filter(None, log::LevelFilter::Warn);
    clog.init();
}

fn main() -> download::Except<()> {
    log_inif();
    let opts = Opts::parse();

    download::set_tmp_dir(&opts.output_dir);

    let _ = opts
        .urls
        .iter()
        .map(|url| {
            info!("ready for {}  [{}]", url.yellow(), "wait".blue());
            if !url.ends_with(&opts.file_type) && opts.file_type != "[NONE]" {
                let vec = download::filter_file_from_url(&url, &opts.file_type);
                let _ = vec
                    .iter()
                    .map(|url| {
                        let _ = match download::DownloadObject::new(&url, opts.thread) {
                            Ok(obj) => {
                                obj.download();
                            }
                            Err(e) => {
                                log::error!(
                                    "{} download [{}] | reason \n{}",
                                    url.yellow(),
                                    "X".red(),
                                    e
                                );
                            }
                        };
                    })
                    .collect::<Vec<_>>();
            } else {
                let _ = match download::DownloadObject::new(&url, opts.thread) {
                    Ok(obj) => {
                        obj.download();
                    }
                    Err(e) => {
                        log::error!("{} download [{}] | reason:\n{}", url.yellow(), "X".red(), e);
                    }
                };
            }
        })
        .collect::<Vec<_>>();
    // download::wait_all_download();
    Ok(())
}
